package com.monkey.service;

import com.monkey.util.WebConfig;
import com.monkey.util.order.WKCOrderUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * desc:
 * auth: chenxiaobin
 * data: 2018/1/11.
 */
@Service
@Transactional
public class TaskService {
    private static Logger logger = LoggerFactory.getLogger(TaskService.class);
    private ScheduledExecutorService schedule = null;
    private ScheduledFuture<?> scheduledFuture = null;

    @Resource
    private BonusService bonusService = null;

    @Resource
    private WKCOrderUtil wkcOrderUtil = null;

    @Resource
    private WebConfig webConfig = null;

    public void init() {
        wkcOrderUtil.init();

        int delay = webConfig.getInt("task.time.delay");
        schedule = Executors.newScheduledThreadPool(1);
        scheduledFuture = schedule.scheduleWithFixedDelay(new MyRunnable(), delay, delay, TimeUnit.SECONDS);
    }

    public void close() {
        if (null != scheduledFuture) {
            scheduledFuture.cancel(true);
            scheduledFuture = null;
            schedule.shutdownNow();
        }
    }

    // 掘金分红定时器
    @Scheduled(cron = "0 5 0 * * * ")
    public void bonus() {
        bonusService.countBonus();
    }

    // 订单查询定时器
    public class MyRunnable implements Runnable {

        @Override
        public void run() {
            logger.info("----- task start -----");
            try {
                wkcOrderUtil.handle();
            } catch (Exception e) {
                logger.info("task error:{}", e);
            }
            logger.info("----- task end -----");
        }
    }
}
